<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Redf;
use App\Models\MyLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

require_once('function.php');
require_once('moban.php');


class WePayController extends Controller
{

    /**
     * @微信支付
     * @return array
     */
    public function WePay(Request $request)
    {

        $orderData = Input::all();
        $badword = badword();
        //敏感词识别
        $bad = transgress_keyword($orderData['text'],$badword);
        if ($bad>0) {
            return response()->json(['code' => 200, 'status' => 0, 'message' => '语音口令不允许输入敏感词！']);
        }

        if (empty($orderData['openid'])) {
            return response()->json(['code' => 200, 'status' => 0, 'message' => '该用户未注册']);
        }
        $model = new Order;
        $type = 'parcel_detail';
        //判断是猜对有钱则上传语音
        if($orderData['sign'] == 2){
            $orderData['voice_url'] =  $model->cdvoiceUpload();
            $type = 'guess';
        }

        //零钱支付判断
        if (false !== $red = $model->wallet_money($orderData)) {
            $wxurl = get_wximg($orderData['avatarurl'], $red['redfid']);
            $moban = new \Moban();
            $wxkey = $red['password'];
            if ($orderData['sign'] == 2) {
                $wxkey = '******';
            }
            $moban->wxcode($red['redfid'], $wxkey , $wxurl,$type);
            @unlink('./wxcode/' . $red['redfid'] . '.png');
            $data['code_url'] = 'https://hd.huwaishequ.com/kxred/public/wxcode/wx' . $red['redfid'] . '.png';
            $data['redid'] = $red['redfid'];
            return response()->json(['code' => 200, 'status' => 1, 'message' => '提交成功', 'data' => $data, 'pay_type' => 1]);
        }



        /*
         * 下单开始
         *
         * */

        if (false !== $orderInfo = $model->orderAdd($orderData)) {
            $order = Order::where('order_sn', $orderInfo)->where('pay_status', 0)->first();
            if (!$order) {
                return response()->json(['code' => 200, 'status' => 0, 'message' => '数据异常！']);
            }

            //统一下单参数构造
            $unifiedorder = array(
                'appid' => env('APP_ID'),//appid
                'mch_id' => env('WXPAY_MCHID'),//商户号
                'nonce_str' => $this->getNonceStr(),//随机字符串
                'body' => '语音红包',
                'out_trade_no' => $order->order_sn,//订单号
                'total_fee' => $order->price * 100,//价格
                'spbill_create_ip' => $request->getClientIp(),//获取ip
                'notify_url' => 'https://hd.huwaishequ.com/kxred/public/api/notify',//这里最好用http，回调不成功查看网络
                'trade_type' => 'JSAPI',
                'openid' => $order->open_id,
                'limit_pay'=>'no_credit',//指定不能使用信用卡支付
            );
            $unifiedorder['sign'] = $this->makeSign($unifiedorder);


            //请求数据
            $xmldata = $this->array2xml($unifiedorder);
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
            $res = $this->curl_post_ssl($url, $xmldata);

            if (!$res) {
                return response()->json(['code' => 200, 'status' => 0, 'message' => '无法连接服务器']);
            }

            $content = $this->xml2array($res);
            $result_code = isset($content['result_code']) ? $content['result_code'] : '';
            $return_code = isset($content['return_code']) ? $content['return_code'] : '';
            if (strval($result_code) == 'FAIL') {
                return $this->return_err(strval($content['err_code_des']));
            }
            if (strval($return_code) == 'FAIL') {
                return $this->return_err(strval($content['return_msg']));
            }
            $data = $this->pay($content['prepay_id']);

            /*
             * 最终返回调起支付
             *
             * */

            DB::table('cdorder')->where('order_sn', $order->order_sn)->update(['prepay_id' => $content['prepay_id']]);
            $redfid = Redf::where('order_sn', $order->order_sn)->first();
            $redfID = $redfid->id;//发红包的id

            $wxurl = get_wximg($orderData['avatarurl'], $redfID);
            $moban = new \Moban();
            $wxkey = $redfid->password;
            if ($orderData['sign'] == 2) {
                $wxkey = '******';
            }
            $wxcode = $moban->wxcode($redfID, $wxkey, $wxurl,$type);
            @unlink('./wxcode/' . $redfID . '.png');
            $data['code_url'] = 'https://hd.huwaishequ.com/kxred/public/wxcode/wx' . $redfID . '.png';
            $data['redid'] = $redfID;
            return response()->json(['code' => 200, 'status' => 1, 'message' => '提交成功', 'data' => $data, 'pay_type' => 0]);
        }

    }


    /**
     * 进行支付接口签名
     * @param string $prepay_id 预支付ID(调用prepay()方法之后的返回数据中获取)
     * @return  json的数据
     */
    public function pay($prepay_id)
    {
        $data = array(
            'appId' => env('APP_ID'),
            'timeStamp' => time(),
            'nonceStr' => $this->getNonceStr(),
            'package' => 'prepay_id=' . $prepay_id,
            'signType' => 'MD5'
        );
        $data['paySign'] = $this->makeSign($data);
        return $data;
    }

//---------------------------------------------------------------用到的函数------------------------------------------------------------

    /**
     * 错误返回提示
     * @param string $errMsg 错误信息
     * @param string $status 错误码
     * @return  json的数据
     */
    protected function return_err($errMsg = 'error', $status = 0)
    {
        return response()->json(['code' => 200, 'result' => 'fail', 'status' => $status, 'errmsg' => $errMsg]);
    }

    /**
     * 正确返回
     * @param     array $data 要返回的数组
     * @return  json的数据
     */
    protected function return_data($data = array())
    {
        return response()->json(['code' => 200, 'result' => 'success', 'status' => 1, 'data' => $data]);
    }

    /**
     * 将一个数组转换为 XML 结构的字符串
     * @param array $arr 要转换的数组
     * @param int $level 节点层级, 1 为 Root.
     * @return string XML 结构的字符串
     */
    protected function array2xml($arr, $level = 1)
    {
        $s = $level == 1 ? "<xml>" : '';
        foreach ($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value['TagName']);
            }
            if (!is_array($value)) {
                $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . $this->array2xml($value, $level + 1) . "</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
        return $level == 1 ? $s . "</xml>" : $s;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array    转换得到的数组
     */
    protected function xml2array($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }

    /**
     *
     * 产生随机字符串，不长于32位
     * @param int $length
     * @return 产生的随机字符串
     */
    protected function getNonceStr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 生成签名
     * @return 签名
     */
    protected function makeSign($data)
    {
        //获取微信支付秘钥
        $key = env('WXPAY_API_KEY');
        // 去空
        $data = array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a = http_build_query($data);
        $string_a = urldecode($string_a);
        //签名步骤二：在string后加入KEY
        //$config=$this->config;
        $string_sign_temp = $string_a . "&key=" . $key;
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result = strtoupper($sign);
        return $result;
    }

    /**
     * 微信支付发起请求
     */
    protected function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            curl_close($ch);
            return false;
        }
    }


}